package com.zjh.photoshopstudy.app.video;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.dueeeke.videocontroller.StandardVideoController;
import com.dueeeke.videocontroller.component.PrepareView;
import com.dueeeke.videocontroller.component.TitleView;
import com.dueeeke.videocontroller.component.VodControlView;
import com.dueeeke.videoplayer.player.VideoView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.zjh.photoshopstudy.Model.CommentEntity;
import com.zjh.photoshopstudy.Model.HistoryEntity;
import com.zjh.photoshopstudy.Model.VideoEntity;
import com.zjh.photoshopstudy.R;
import com.zjh.photoshopstudy.Utils.CheckWordUtil;
import com.zjh.photoshopstudy.Utils.CommentImageClick;
import com.zjh.photoshopstudy.Utils.Data;
import com.zjh.photoshopstudy.Utils.SharePreferencesUtils;
import com.zjh.photoshopstudy.app.login.LoginActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class VideoActivity extends AppCompatActivity {
    private static final String TAG = "VideoActivity";
    private VideoPresent present;
    private VideoView mVideoView;
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private VideoEntity mVideoEntity;
    private EditText mEditText;
    private CommentEntity mReplayCommentEntity;
    private List<String> uris = new ArrayList<>();
    private Fragment commentFragment;
    private Fragment videoInfoFragment;
    private boolean isCollection = false;
    private boolean isLogin = false;
    private Button collectBtn;
    private int videoDownloadState = 0;
    private int materiaDownloadState = 0;

    private OnCommentClickListener commentClickListener = new OnCommentClickListener() {
        @Override
        public void onClick(CommentEntity commentEntity) {
            mReplayCommentEntity = commentEntity;
            mEditText.setText("");
            mEditText.setHint("回复 " + commentEntity.getAppUserEntity().getuName() + " : ");
            uris.clear();
            mEditText.setSelection(0);
            mEditText.setFocusable(true);
            mEditText.setFocusableInTouchMode(true);
            mEditText.requestFocus();
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        present = new VideoPresent(this);
        setContentView(R.layout.activity_video);
        mVideoEntity = (VideoEntity) getIntent().getSerializableExtra("videoEntity");

        List<DownloadTask> taskList = OkDownload.restore(DownloadManager.getInstance().getAll());
        for (DownloadTask task : taskList) {
            Progress progress = task.progress;
            VideoEntity entity1 = (VideoEntity) task.progress.extra1;
            VideoEntity entity2 = (VideoEntity) task.progress.extra2;
            if (entity1 != null && entity1.getId() == mVideoEntity.getId()) {
                videoDownloadState = progress.status;
                if (videoDownloadState == Progress.FINISH) {
                    Uri uri = Uri.parse("file://" + progress.filePath);
                    mVideoEntity.setvPath(uri.toString());
                }
            }
            if (entity2 != null && entity2.getId() == mVideoEntity.getId()) {
                materiaDownloadState = progress.status;
            }
        }
        if (videoDownloadState != Progress.FINISH) {
            present.getVideo(mVideoEntity.getId());
        } else {
            getVideoSuccess(mVideoEntity);
        }
    }

    public void getVideoSuccess(VideoEntity videoEntity) {
        mVideoEntity = videoEntity;
        initPlayer();
        initViewPager();
    }

    private void initViewPager() {
        mTabLayout = findViewById(R.id.tab);
        mViewPager = findViewById(R.id.viewpager);
        mEditText = findViewById(R.id.editText);

        isCollection = present.IsCollection((int) mVideoEntity.getId());
        isLogin = present.IsLoginUser();


        mEditText.setMovementMethod(LinkMovementMethod.getInstance());
        commentFragment = new VideoCommentFragment();
        ((VideoCommentFragment) commentFragment).setCommentClickListener(commentClickListener);
        videoInfoFragment = new VideoInfoFragment();
        ((VideoInfoFragment) videoInfoFragment).setCollection(isCollection);
        ((VideoInfoFragment) videoInfoFragment).setLogin(isLogin);
        ((VideoInfoFragment) videoInfoFragment).setVideoDownloadState(videoDownloadState);
        ((VideoInfoFragment) videoInfoFragment).setMateriaDownloadState(materiaDownloadState);
        final List<Fragment> list = new ArrayList<>();
        list.add(videoInfoFragment);
        list.add(commentFragment);
        mTabLayout.addTab(mTabLayout.newTab());
        mTabLayout.addTab(mTabLayout.newTab());
        mTabLayout.setupWithViewPager(mViewPager, false);
        Bundle bundle = new Bundle();
        bundle.putSerializable("videoEntity", mVideoEntity);
        bundle.putLong("Duration", mVideoView.getDuration());
        videoInfoFragment.setArguments(bundle);
        commentFragment.setArguments(bundle);
        FragmentPagerAdapter adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return list.get(position);
            }

            @Override
            public int getCount() {
                return list.size();
            }
        };
        mViewPager.setAdapter(adapter);
        mTabLayout.getTabAt(0).setText("详情");
        mTabLayout.getTabAt(1).setText("评论");
        mEditText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_DEL) {
                    EditText editText = ((EditText) view);
                    String text = editText.getText().toString();
                    int curr = editText.getSelectionStart();
                    if (curr < 0) {
                        mReplayCommentEntity = null;
                        mEditText.setHint("");
                        return false;
                    }
                    String temp = text.substring(0, curr);
                    String s = "查看图片 ";
                    if (temp.endsWith(s)) {
                        int index = -1;
                        do {
                            index++;
                            temp = temp.substring(0, temp.lastIndexOf(s));
                        } while (temp.contains(s));
                        uris.remove(index);
                        int c = curr - s.length();
                        String newText = text.substring(0, c) + text.substring(curr);
                        editText.setText(getSpannableString(newText, s));
                        editText.setSelection(curr - s.length());
                    }
                    Log.e(TAG, "onKey: ");
                }
                return false;
            }
        });

    }


    private void initPlayer() {

        List<HistoryEntity> list = SharePreferencesUtils.getHistory(this);
        mVideoView = findViewById(R.id.player);
        if (list != null) {
            for (HistoryEntity e : list) {
                if (e.getId() == mVideoEntity.getId()) {
                    mVideoView.skipPositionWhenPlay((int) (e.getCurrent()));
                }
            }
        }
        PrepareView prepareView = new PrepareView(this);//准备播放界面
        ImageView thumb = prepareView.findViewById(R.id.thumb);//封面图
        Glide.with(this).load(Data.webRoot_URL + mVideoEntity.getvThumbnailPath()).into(thumb);
        if (videoDownloadState == Progress.FINISH) {
            mVideoView.setUrl(mVideoEntity.getvPath());
        } else {
            mVideoView.setUrl(Data.webRoot_URL + mVideoEntity.getvPath()); //设置视频地址
        }
        StandardVideoController controller = new StandardVideoController(this);
        VodControlView vodControlView = new VodControlView(this);//点播控制条
        controller.addControlComponent(vodControlView);
        TitleView titleView = new TitleView(this);//标题栏
        controller.addControlComponent(titleView);
        controller.addControlComponent(prepareView);
        titleView.setTitle(mVideoEntity.getvTitle());
        mVideoView.setVideoController(controller); //设置控制器
        mVideoView.setLooping(true);
        mVideoView.start();
        /*controller.setListener
        mVideoView.setListener*/
        /*mVideoView.setOnStateChangeListener(new VideoView.OnStateChangeListener() {
            @Override
            public void onPlayerStateChanged(int playerState) {
                if (playerState == VideoView.STATE_PLAYING) {
                    ((VideoInfoFragment) videoInfoFragment).setTime(mVideoView.getDuration());
                }
            }

            @Override
            public void onPlayStateChanged(int playState) {

            }
        });*/
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            uris.add(uri.toString());
            String s = "查看图片 ";
            String text = mEditText.getText().toString() + s;
            mEditText.setText(getSpannableString(text, s));
            mEditText.setSelection(text.length());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void onClick(View view) {
        if (!isLogin) {
            toLogin();
            return;
        }
        switch (view.getId()) {
            case R.id.addBtn:
                Intent intent1 = new Intent(Intent.ACTION_PICK);
                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                Intent chooser = Intent.createChooser(intent1, "选择图片");
                startActivityForResult(chooser, 100);
                break;
            case R.id.send:
                sendComment();
                break;
            case R.id.collectBtn:
                if (!isCollection) {
                    doCollection();
                } else {
                    doCancelCollection();
                }
                break;
            case R.id.videoDownloadBtn:
                if (videoDownloadState != Progress.FINISH && videoDownloadState != Progress.LOADING) {
                    downloadVideo();
                }
                break;
            case R.id.materiaDownloadBtn:
                if (materiaDownloadState != Progress.FINISH && materiaDownloadState != Progress.LOADING) {
                    downloadMateria();
                }
                break;
            case R.id.imageButton:
                Intent intent = new Intent(this,ShareDialog.class);
                intent.putExtra("video",mVideoEntity);
                startActivity(intent);
                break;
        }
    }

    private void downloadMateria() {
        //这里只是演示，表示请求可以传参，怎么传都行，和okgo使用方法一样
        GetRequest<File> request = OkGo.<File>get(Data.webRoot_URL + mVideoEntity.getvMateriaPath())//
                .headers("aaa", "111")//
                .params("bbb", "222");

        //这里第一个参数是tag，代表下载任务的唯一标识，传任意字符串都行，需要保证唯一,我这里用url作为了tag
        OkDownload.request(mVideoEntity.getvMateriaPath() + mVideoEntity.getId(), request)//
                .extra2(mVideoEntity)//
                .save()//
                .register(new ListDownloadListener(1, 1))
                .start();
    }

    private void downloadVideo() {
        //这里只是演示，表示请求可以传参，怎么传都行，和okgo使用方法一样
        GetRequest<File> request = OkGo.<File>get(Data.webRoot_URL + mVideoEntity.getvPath())//
                .headers("aaa", "111")//
                .params("bbb", "222");

        //这里第一个参数是tag，代表下载任务的唯一标识，传任意字符串都行，需要保证唯一,我这里用url作为了tag
        OkDownload.request(mVideoEntity.getvPath() + mVideoEntity.getId(), request)//
                .extra1(mVideoEntity)//
                .save()//
                .register(new ListDownloadListener(1, 0))
                .start();
    }

    private void toLogin() {
        startActivity(new Intent(this, LoginActivity.class));
    }

    private void doCancelCollection() {
        present.doCancelCollection(mVideoEntity);
    }

    private void doCollection() {
        present.Collection(mVideoEntity);
    }

    private void sendComment() {
        String text = mEditText.getText().toString().trim();
        if (text.length()==0){
            Toast.makeText(this, "评论不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (CheckWordUtil.getInstance(this).checkWord(text)) {
            present.sendComment(mReplayCommentEntity, mVideoEntity, text, uris);
        } else {
            Toast.makeText(this, "评论有违规词汇！", Toast.LENGTH_SHORT).show();
        }

    }

    public void onSendCommentSuccess(CommentEntity commentEntity) {
        Toast.makeText(this, "发送成功", Toast.LENGTH_SHORT).show();
        mEditText.setHint("");
        mEditText.setText("");
        mReplayCommentEntity = null;
        ((VideoCommentFragment) commentFragment).onSendCommentSuccess(commentEntity);
    }

    public void onSendCommentFail() {
        Toast.makeText(this, "发送失敗", Toast.LENGTH_SHORT).show();
    }

    private SpannableStringBuilder getSpannableString(String text, String s) {
        SpannableStringBuilder spannable = new SpannableStringBuilder();
        String str = text;
        int index = 0;
        while (str.contains(s)) {
            spannable.append(str.substring(0, str.indexOf(s)));
            int start = spannable.length();
            CommentImageClick clickableSpan = new CommentImageClick(this, uris.get(index));
            spannable.append(s);
            int end = start + s.length() - 1;
            spannable.setSpan(clickableSpan, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#FF00B8D4"));
            spannable.setSpan(colorSpan, start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            str = str.substring(str.indexOf(s) + s.length());
            index++;
        }
        spannable.append(str);
        return spannable;
    }

    @Override
    protected void onPause() {
        present.saveHistory(mVideoEntity, mVideoView.getCurrentPosition());
        super.onPause();
        if (mVideoView != null)
            mVideoView.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mVideoView != null)
            mVideoView.resume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mVideoView != null)
            mVideoView.release();
    }


    @Override
    public void onBackPressed() {
        if (mVideoView != null && !mVideoView.onBackPressed()) {
            super.onBackPressed();
        }
    }


    public void onCollectionSuccess() {
        Toast.makeText(this, "收藏成功", Toast.LENGTH_SHORT).show();
        isCollection = true;
        ((VideoInfoFragment) videoInfoFragment).onCollectionSuccess();
    }

    public void onCollectionFail() {
        Toast.makeText(this, "收藏失败", Toast.LENGTH_SHORT).show();
    }

    public void onCancelCollectionSuccess() {
        Toast.makeText(this, "取消收藏成功", Toast.LENGTH_SHORT).show();
        isCollection = false;
        ((VideoInfoFragment) videoInfoFragment).onCancelCollectionSuccess();
    }

    public void onCancelCollectionFail() {
        Toast.makeText(this, "取消收藏失败", Toast.LENGTH_SHORT).show();
    }

    private class ListDownloadListener extends DownloadListener {
        int type;

        ListDownloadListener(Object tag, int type) {
            super(tag);
            this.type = type;
        }

        @Override
        public void onStart(Progress progress) {
            Toast.makeText(VideoActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
            updateState(Progress.LOADING);
        }

        @Override
        public void onProgress(Progress progress) {
        }

        @Override
        public void onError(Progress progress) {
            Toast.makeText(VideoActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
            updateState(Progress.NONE);
        }

        @Override
        public void onFinish(File file, Progress progress) {
            Toast.makeText(VideoActivity.this, "下载完成:" + progress.filePath, Toast.LENGTH_SHORT).show();
            updateState(Progress.FINISH);
        }

        @Override
        public void onRemove(Progress progress) {
        }

        private void updateState(int state) {
            if (type == 0) {
                videoDownloadState = state;
            } else {
                materiaDownloadState = state;
            }
            ((VideoInfoFragment) videoInfoFragment).updateBtn(videoDownloadState, materiaDownloadState);
        }
    }
}
